package com.example.demo.service;

import com.example.demo.entity.Memorandum;
import com.example.demo.repository.MemorandumRepository;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class QuartzService {

    @Autowired
    MemorandumRepository memorandumRepository;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void timerToNow() {
        SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        String formatStr2 =formatter2.format(new Date());
        Long time = System.currentTimeMillis();
        time +=1000*60;
        SimpleDateFormat formatter3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
        String formatStr4 =formatter3.format(new Date(time));
        List<Memorandum> list = memorandumRepository.findByMemorandumStart(formatStr2,formatStr4);
        if(list.size()>0){
            // 这里是整理推送需要的信息
            String appId ="A6082620331755";
            String appKey = "FC59B9E0-640C-2732-145C-847DDEB34140";
            String url = "https://p.apicloud.com/api/push/message";

            Map<String,String> headers = new HashMap<String,String>();
            headers.put("X-APICloud-AppId", appId);
            headers.put("X-APICloud-AppKey", encrypt(appId,appKey,"SHA-1"));
            headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            Map<String,String> params = new HashMap<String,String>();
            params.put("title", "你有"+list.size()+"条备忘录需要处理哦-。-！");
            params.put("content", "请尽快处理！");
            params.put("type", 2+"");
            params.put("platform", 2+"");
            // 这里开始请求
            HttpClient client = new HttpClient();
            PostMethod postMethod = new PostMethod(url);
            //设置header
            setHeaders(postMethod,headers);
            //设置post请求参数
            setParams(postMethod,params);
            String responseStr = "";

            try {
                client.executeMethod(postMethod);
                responseStr = postMethod.getResponseBodyAsString();
            } catch (Exception e) {
                e.printStackTrace();
                responseStr="{status:0}";
            }

        }
    }

    /**
     * 设置请求参数
     * @param method
     * @param params
     */
    private static void setParams(PostMethod method,Map<String, String> params) {

        //校验参数
        if(params==null||params.size()==0){
            return;
        }

        Set<String> paramsKeys = params.keySet();
        Iterator<String> iterParams = paramsKeys.iterator();
        while(iterParams.hasNext()){
            String key = iterParams.next();
            method.addParameter(key, params.get(key));
        }

    }
    /**
     * 设置请求头部信息
     * @param method
     * @param headers
     */
    private static void setHeaders(HttpMethod method, Map<String, String> headers) {
        Set<String> headersKeys = headers.keySet();
        Iterator<String> iterHeaders = headersKeys.iterator();
        while(iterHeaders.hasNext()){
            String key = iterHeaders.next();
            method.setRequestHeader(key, headers.get(key));
        }
    }
    /**
     * 执行加密算法
     * @param encName 加密规则
     * @return
     */
    public static String encrypt(String appId,String appKey, String encName) {

        Date date = new Date();
        Long time = date.getTime();

        String strSrc = appId+"UZ"+appKey+"UZ" + time;

        MessageDigest md = null;
        String strDes = null;

        byte[] bt = strSrc.getBytes();
        try {
            if (encName == null || encName.equals("")) {
                encName = "MD5";
            }
            md = MessageDigest.getInstance(encName);
            md.update(bt);
            strDes = bytes2Hex(md.digest())+ "." + time; // to HexString
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
        return strDes;
    }

    private static String bytes2Hex(byte[] bts) {
        String des = "";
        String tmp = null;
        for (int i = 0; i < bts.length; i++) {
            tmp = (Integer.toHexString(bts[i] & 0xFF));
            if (tmp.length() == 1) {
                des += "0";
            }
            des += tmp;
        }
        return des;
    }

}
